//
//  UIApplication+ShowNetwork.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-9-13.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "UIApplication+ShowNetwork.h"

#import <objc/runtime.h>

#import "LoadableCategory.h"
MAKE_CATEGORIES_LOADABLE(MFWSdk_UIApplication_ShowNetwork)

@interface UIApplication(_showNetwork)

@property (nonatomic, readonly) NSMutableDictionary *networkActivityIndicatorVisibleDict;

@end

const char *networkActivityIndicatorVisibleDictKey =
"networkActivityIndicatorVisibleDictKey";

@implementation UIApplication(_showNetwork)

- (NSMutableDictionary*)networkActivityIndicatorVisibleDict
{
    NSMutableDictionary *dict = objc_getAssociatedObject(self, networkActivityIndicatorVisibleDictKey);
    if (!dict)
    {
        dict = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, networkActivityIndicatorVisibleDictKey, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return dict;
}

@end



@implementation UIApplication (ShowNetwork)


- (void)setNetworkActivityIndicatorVisible:(BOOL)aVisiable forKey:(NSString *)aKey
{
    if ([self networkActivityIndicatorVisibleForKey:aKey] == aVisiable)
    {
        return;
    }
    
    if (aVisiable)
    {
        if (self.networkActivityIndicatorVisibleDict.allKeys.count == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.networkActivityIndicatorVisible = YES;
            });
        }
        [self.networkActivityIndicatorVisibleDict setValue:[NSNull null]
                                                    forKey:aKey];
    }
    else
    {
        [self.networkActivityIndicatorVisibleDict removeObjectForKey:aKey];
        if (self.networkActivityIndicatorVisibleDict.allKeys.count == 0)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.networkActivityIndicatorVisible = NO;
            });
        }
    }
}

- (BOOL)networkActivityIndicatorVisibleForKey:(NSString *)aKey
{
    id value = [self.networkActivityIndicatorVisibleDict valueForKey:aKey];
    if (value)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


@end
